package com.chengqs.interceptor;

import com.chengqs.common.UserContext;
import com.chengqs.pojo.entity.User;
import com.chengqs.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            // 当前拦截到的不是动态方法，直接放行
            return true;
        }
        // 1、从请求头中获取令牌
        String token = request.getHeader("Authorization");

        Claims claims = JwtUtil.checkJWT(token);

        if(claims == null){
            //response.sendRedirect("/dev/views/login.html");
            return false;
        }

        User user = new User();
        Integer id = (Integer) claims.get("id");
        String username = (String) claims.get("username");
        user.setId(id.longValue());
        user.setUsername(username);

        UserContext.setCurrentUser(user);
        return true;
    }
}
